package org.jeecg.modules.ncmeapis.template.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.swagger.BusinessApi;
import org.jeecg.modules.ncmeapis.template.service.ISysPackTemplatePremsService;
import org.jeecg.modules.ncmeapis.template.service.ISysPackTemplateService;
import org.jeecg.modules.ncmeapis.template.entity.SysPackTemplate;
import org.jeecg.modules.ncmeapis.template.entity.SysPackTemplatePrems;
import org.jeecg.modules.ncmeapis.template.vo.SysPackTemplatePage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
* @Description: 用户角色模板
* @Author: jeecg-boot
* @Date:   2023-12-18
* @Version: V1.0
*/
@Api(tags="用户角色模板")
@RestController
@RequestMapping("/sysBaoTou/packTemplate")
@BusinessApi
@Slf4j
public class SysPackTemplateController {
   @Autowired
   private ISysPackTemplateService sysPackTemplateService;
   @Autowired
   private ISysPackTemplatePremsService sysPackTemplatePremsService;

   /**
    * 分页列表查询
    *
    * @param sysPackTemplate
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   //@AutoLog(value = "用户角色模板-分页列表查询")
   @ApiOperation(value="用户角色模板-分页列表查询", notes="用户角色模板-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<SysPackTemplate>> queryPageList(SysPackTemplate sysPackTemplate,
                                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                       HttpServletRequest req) {
       QueryWrapper<SysPackTemplate> queryWrapper = QueryGenerator.initQueryWrapper(sysPackTemplate, req.getParameterMap());
       Page<SysPackTemplate> page = new Page<SysPackTemplate>(pageNo, pageSize);
       IPage<SysPackTemplate> pageList = sysPackTemplateService.page(page, queryWrapper);
       return Result.OK(pageList);
   }

    /**
     * 查询所有项目角色
     *
     * @param sysPackTemplate
     * @param req
     * @return
     */
    //@AutoLog(value = "用户角色模板-分页列表查询")
    @ApiOperation(value="所有项目角色", notes="查询所有项目角色")
    @GetMapping(value = "/queryAllPackTemplate")
    public Result<List<SysPackTemplate>> queryAllPackTemplate(SysPackTemplate sysPackTemplate, HttpServletRequest req) {
        QueryWrapper<SysPackTemplate> queryWrapper = QueryGenerator.initQueryWrapper(sysPackTemplate, req.getParameterMap());
        List<SysPackTemplate> list = sysPackTemplateService.list(queryWrapper);
        return Result.OK(list);
    }

   /**
    *   添加
    *
    * @param sysPackTemplatePage
    * @return
    */
   @AutoLog(value = "用户角色模板-添加")
   @ApiOperation(value="用户角色模板-添加", notes="用户角色模板-添加")
   @RequiresPermissions("template:sys_pack_template:add")
   @PostMapping(value = "/add")
   public Result<String> add(@RequestBody SysPackTemplatePage sysPackTemplatePage) {
       SysPackTemplate sysPackTemplate = new SysPackTemplate();
       BeanUtils.copyProperties(sysPackTemplatePage, sysPackTemplate);
       sysPackTemplateService.saveMain(sysPackTemplate, sysPackTemplatePage.getSysPackTemplatePremsList());
       return Result.OK("添加成功！");
   }

   /**
    *  编辑
    *
    * @param sysPackTemplatePage
    * @return
    */
   @AutoLog(value = "用户角色模板-编辑")
   @ApiOperation(value="用户角色模板-编辑", notes="用户角色模板-编辑")
   @RequiresPermissions("template:sys_pack_template:edit")
   @PutMapping(value = "/edit")
   public Result<String> edit(@RequestBody SysPackTemplatePage sysPackTemplatePage) {
       SysPackTemplate sysPackTemplate = new SysPackTemplate();
       BeanUtils.copyProperties(sysPackTemplatePage, sysPackTemplate);
       SysPackTemplate sysPackTemplateEntity = sysPackTemplateService.getById(sysPackTemplate.getId());
       if(sysPackTemplateEntity==null) {
           return Result.error("未找到对应数据");
       }
       sysPackTemplateService.updateMain(sysPackTemplate, sysPackTemplatePage.getSysPackTemplatePremsList());
       return Result.OK("编辑成功!");
   }

    /**
     *  指定项目id为模板对用户产品包模板进行刷新
     * @param tenantId
     * @return
     */
    @AutoLog(value = "根据项目id更新角色模板")
    @ApiOperation(value="根据项目id更新角色模板", notes="根据项目id更新角色模板")
    @PutMapping(value = "/saveOrUpdateMain")
    public Result<List<SysPackTemplatePage>> saveOrUpdateMain(@RequestParam(name="tenantId",required = true) Integer tenantId) {
        List<SysPackTemplatePage> sysPackTemplatePages = sysPackTemplateService.saveOrUpdateMain(tenantId);
        if(sysPackTemplatePages.size()==0) {
            return Result.error("未找到对应数据");
        }
        return Result.OK("更新角色模板成功!");
    }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "用户角色模板-通过id删除")
   @ApiOperation(value="用户角色模板-通过id删除", notes="用户角色模板-通过id删除")
   @RequiresPermissions("template:sys_pack_template:delete")
   @DeleteMapping(value = "/delete")
   public Result<String> delete(@RequestParam(name="id",required=true) String id) {
       sysPackTemplateService.delMain(id);
       return Result.OK("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "用户角色模板-批量删除")
   @ApiOperation(value="用户角色模板-批量删除", notes="用户角色模板-批量删除")
   @RequiresPermissions("template:sys_pack_template:deleteBatch")
   @DeleteMapping(value = "/deleteBatch")
   public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.sysPackTemplateService.delBatchMain(Arrays.asList(ids.split(",")));
       return Result.OK("批量删除成功！");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "用户角色模板-通过id查询")
   @ApiOperation(value="用户角色模板-通过id查询", notes="用户角色模板-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<SysPackTemplate> queryById(@RequestParam(name="id",required=true) String id) {
       SysPackTemplate sysPackTemplate = sysPackTemplateService.getById(id);
       if(sysPackTemplate==null) {
           return Result.error("未找到对应数据");
       }
       return Result.OK(sysPackTemplate);

   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   //@AutoLog(value = "用户角色模板权限表通过主表ID查询")
   @ApiOperation(value="用户角色模板权限表主表ID查询", notes="用户角色模板权限表-通主表ID查询")
   @GetMapping(value = "/querySysPackTemplatePremsByMainId")
   public Result<List<SysPackTemplatePrems>> querySysPackTemplatePremsListByMainId(@RequestParam(name="id",required=true) String id) {
       List<SysPackTemplatePrems> sysPackTemplatePremsList = sysPackTemplatePremsService.selectByMainId(id);
       return Result.OK(sysPackTemplatePremsList);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param sysPackTemplate
   */
   @RequiresPermissions("template:sys_pack_template:exportXls")
   @GetMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, SysPackTemplate sysPackTemplate) {
     // Step.1 组装查询条件查询数据
     QueryWrapper<SysPackTemplate> queryWrapper = QueryGenerator.initQueryWrapper(sysPackTemplate, request.getParameterMap());
     LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
     String selections = request.getParameter("selections");
     if(oConvertUtils.isNotEmpty(selections)) {
        List<String> selectionList = Arrays.asList(selections.split(","));
        queryWrapper.in("id",selectionList);
     }
     //Step.2 获取导出数据
     List<SysPackTemplate> sysPackTemplateList = sysPackTemplateService.list(queryWrapper);

     // Step.3 组装pageList
     List<SysPackTemplatePage> pageList = new ArrayList<SysPackTemplatePage>();
     for (SysPackTemplate main : sysPackTemplateList) {
         SysPackTemplatePage vo = new SysPackTemplatePage();
         BeanUtils.copyProperties(main, vo);
         List<SysPackTemplatePrems> sysPackTemplatePremsList = sysPackTemplatePremsService.selectByMainId(main.getId());
         vo.setSysPackTemplatePremsList(sysPackTemplatePremsList);
         pageList.add(vo);
     }

     // Step.4 AutoPoi 导出Excel
     ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
     mv.addObject(NormalExcelConstants.FILE_NAME, "用户角色模板列表");
     mv.addObject(NormalExcelConstants.CLASS, SysPackTemplatePage.class);
     mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户角色模板数据", "导出人:"+sysUser.getRealname(), "用户角色模板"));
     mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
     return mv;
   }

   /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequiresPermissions("template:sys_pack_template:importExcel")
   @PostMapping(value = "/importExcel")
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
     Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
     for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
         // 获取上传文件对象
         MultipartFile file = entity.getValue();
         ImportParams params = new ImportParams();
         params.setTitleRows(2);
         params.setHeadRows(1);
         params.setNeedSave(true);
         try {
             List<SysPackTemplatePage> list = ExcelImportUtil.importExcel(file.getInputStream(), SysPackTemplatePage.class, params);
             for (SysPackTemplatePage page : list) {
                 SysPackTemplate po = new SysPackTemplate();
                 BeanUtils.copyProperties(page, po);
                 sysPackTemplateService.saveMain(po, page.getSysPackTemplatePremsList());
             }
             return Result.OK("文件导入成功！数据行数:" + list.size());
         } catch (Exception e) {
             log.error(e.getMessage(),e);
             return Result.error("文件导入失败:"+e.getMessage());
         } finally {
             try {
                 file.getInputStream().close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
     return Result.OK("文件导入失败！");
   }

}
